package com.karry.web;

import com.karry.pojo.Blog;
import com.karry.pojo.Comment;
import com.karry.pojo.User;
import com.karry.service.BlogService;
import com.karry.service.CommentService;
import com.karry.service.UserService;
import com.karry.service.impl.BlogServiceImpl;
import com.karry.service.impl.CommentServiceImpl;
import com.karry.service.impl.UserServiceImpl;
import com.karry.util.*;
import com.karry.vo.BlogVo;
import com.karry.vo.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@WebServlet("/index")
public class IndexServlet extends HttpServlet {

    BlogService bs = new BlogServiceImpl();
    CommentService cs = new CommentServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置首页导航高亮
        request.setAttribute("menu_page", "index");

        // 得到用户行为 （判断是什么条件查询：标题查询、日期查询、类型查询）
        String actionName = request.getParameter("actionName");
        // 将用户行为设置到request作用域中 （分页导航中需要获取）
        request.setAttribute("action", actionName);

        System.out.println("index_actionName:" + actionName);

        if (actionName == null){
            actionName = "default";
        }

        switch (actionName){
            case "searchDate":
                String date = request.getParameter("date").trim();
                request.setAttribute("date", date);
                blogList(request, response, null, date, null);
                break;
            case "searchType":
                String typeId = request.getParameter("typeId").trim();
                request.setAttribute("typeId", typeId);
                blogList(request, response, null, null, typeId);
                break;
            case "all":
                blogAll(request, response, null, null, null);
                return;
                //break;
            case "searchTitle":
                request.setCharacterEncoding("utf-8");
                String title = request.getParameter("title");
                request.setAttribute("title", title);
                System.out.println("title:" + title);
                blogAll(request, response, title, null, null);
                return;
            case "getCode":
                sendCode(request, response);
                return;
            /*case "customerService":
                customerService(request, response);
                return;*/
            case "goServer":
                goServer(request, response);
                return;
            case "getNotify":
                getNotify(request, response);
                return;
            default:
                blogList(request, response, null, null, null);
                break;
        }

        // 设置首页动态包含的页面
        request.setAttribute("changePage","note/list.jsp");
        // 请求转发到index.jsp
        request.getRequestDispatcher("index.jsp").forward(request, response);


    }

    private void getNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //先随机
        /*Random r = new Random();
        int s = r.nextInt(2);
        ResultInfo<Comment> resultInfo = new ResultInfo<>();
        Comment comment = new Comment();
        comment.setText("111");
        resultInfo.setResult(comment);
        resultInfo.setCode(s);
        System.out.println(resultInfo);
        JsonUtil.toJson(response, resultInfo);*/

        //获取用户
        User user = (User) request.getSession().getAttribute("user");

        //获取通知
        Comment comment = cs.searchFirstNotify(user.getId());
        ResultInfo<Comment> resultInfo = new ResultInfo<>();
        if (comment != null){
            resultInfo.setCode(1);
            resultInfo.setResult(comment);
            //清除该通知
            int i = cs.updateNotify_(comment.getId());
            System.out.println("清除通知:" + i);
        }else {
            resultInfo.setCode(0);
            System.out.println("无通知");
        }
        JsonUtil.toJson(response, resultInfo);
    }

    private void goServer(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        User user = (User) request.getSession().getAttribute("user");
        request.setAttribute("user", user);
        //设置高亮
        request.setAttribute("menu_page", "customer");
        // 设置首页动态包含的页面
        request.setAttribute("changePage","user/server.jsp");
        // 请求转发到index.jsp
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

    /**
     *  发送邮箱验证码
     */
    private void sendCode(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        //获取时间戳，避免重复发送多次
        Long sendTime = (Long) request.getSession().getAttribute("sendTime");
        if (sendTime != null){
            //获取当前时间
            long l = System.currentTimeMillis();
            l -= sendTime;
            //小于三分钟
            if (l < 180000){
                response.getWriter().write(0);
                return;
            }
        }

        //获取邮箱
        String email = request.getParameter("email").trim();
        int send = new MailUtil().send(email);
        //发送失败
        if (send == -1){
            response.getWriter().write(0 + "");
            return;
        }else {
            //记录时间与验证码与邮箱
            request.getSession().setAttribute("email", email);
            request.getSession().setAttribute("code", send);
            request.getSession().setAttribute("sendTime", System.currentTimeMillis());
            response.getWriter().write(1 + "");
        }

        response.getWriter().close();
    }


    /**
     *  查询所有用户指定要求的博客内容并且跳转到“博客大厅”页面
     *  与blogList的区别是，本方法会查询所有用户的内容，而blogList只查询该会话登录用户内容
     * */
    private void blogAll(HttpServletRequest request, HttpServletResponse response,
                         String title, String date, String typeId) throws IOException, ServletException {
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        // 2. 获取Session作用域中的user对象
        User user = (User) request.getSession().getAttribute("user");
        // 3. 调用Service层查询方法，返回Page对象
        Page<Blog> page = bs.findBlogListByPage(pageNum, pageSize, null, title, date, typeId, 1);

        //获取该数据集合点赞评论状况
        if(page != null && page.getDataList() != null && page.getDataList().size() >= 1){
            //点赞
            ArrayList<Integer> list = DianZanUtil.searchBlogListDianCount(page.getDataList());
            request.setAttribute("dianZanList", list);
            //评论
            ArrayList<Integer> blogCommentSizeList = CommentUtil.getBlogCommentSizeList((ArrayList<Blog>) page.getDataList());
            request.setAttribute("commentList", blogCommentSizeList);
        }

        //设置高亮
        request.setAttribute("title", title);
        request.setAttribute("menu_page", "all");
        // 4. 将page对象设置到request作用域中
        request.setAttribute("page", page);
        // 设置首页动态包含的页面
        request.setAttribute("changePage","note/allNote.jsp");
        // 请求转发到index.jsp
        request.getRequestDispatcher("index.jsp").forward(request, response);

    }


    /**
     * 分页查询云记列表
     1. 接收参数 （当前页、每页显示的数量）
     2. 获取Session作用域中的user对象
     3. 调用Service层查询方法，返回Page对象
     4. 将page对象设置到request作用域中
     * @param request
     * @param response
     * @param title 标题
     */
    private void blogList(HttpServletRequest request, HttpServletResponse response,
                          String title, String date, String typeId) {
        // 1. 接收参数 （当前页、每页显示的数量）
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        // 2. 获取Session作用域中的user对象
        User user = (User) request.getSession().getAttribute("user");

        // 3. 调用Service层查询方法，返回Page对象
        Page<Blog> page = bs.findBlogListByPage(pageNum, pageSize, user.getId(), title, date, typeId, 0);
        //获取该数据集合点赞评论状况
        if(page != null && page.getDataList() != null && page.getDataList().size() >= 1){
            //点赞
            ArrayList<Integer> list = DianZanUtil.searchBlogListDianCount(page.getDataList());
            request.setAttribute("dianZanList", list);
            //评论
            ArrayList<Integer> blogCommentSizeList = CommentUtil.getBlogCommentSizeList((ArrayList<Blog>) page.getDataList());
            request.setAttribute("commentList", blogCommentSizeList);
        }

        //查询新通知
        ArrayList<Comment> comments = CommentUtil.searchNotify(user.getId());
        request.getSession().setAttribute("comments", comments);

        // 4. 将page对象设置到request作用域中
        request.setAttribute("page", page);

        // 通过日期分组查询当前登录用户下的云记数量
        List<BlogVo> dateInfo = bs.findNoteCountByDate(user.getId());
        // 设置集合存放在request作用域中
        request.getSession().setAttribute("dateInfo", dateInfo);

        // 通过类型分组查询当前登录用户下的云记数量
        List<BlogVo> typeInfo = bs.findNoteCountByType(user.getId());
        // 设置集合存放在request作用域中
        request.getSession().setAttribute("typeInfo", typeInfo);

    }

}
